package com.sdkx.wear_os.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * 获取定位信息
 */
public class LocationUtils {
    LocationListener listener;
    //定位次数
    private int count = 0;

    public interface LocationCallBack {
        void getLocation(Location location);

        void getAddress(Address address);
    }

    // 获取当前位置经纬度
    @SuppressLint("MissingPermission")
    public void getCurrentLocation(Context mContext, LocationCallBack callBack) {
        LocationManager locationManager =
                (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            listener = new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    count++;
                    //10次之后移除监听
                    if (count >= 10) {
                        locationManager.removeUpdates(listener);
                    }
                    callBack.getLocation(location);
                    Geocoder geocoder = new Geocoder(mContext, Locale.CHINA);
                    try {
                        List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),
                                location.getLongitude(), 1);
                        if (addresses != null && !addresses.isEmpty()) {
                            Address address = addresses.get(0);
                            callBack.getAddress(address);
                            locationManager.removeUpdates(listener);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                @Override
                public void onProviderDisabled(@NonNull String provider) {
                }

                @Override
                public void onProviderEnabled(@NonNull String provider) {
                }
            };
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    0,
                    0F,
                    listener
            );
        }
    }
}